package com.example.cores_sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class SQLiteActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tvMessage;
    private String databasePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sqlite);

        tvMessage = findViewById(R.id.tv_msg);
        findViewById(R.id.btn_create).setOnClickListener(this);
        findViewById(R.id.btn_delete).setOnClickListener(this);

        databasePath = getFilesDir() + "/test.db";
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        boolean isDelete = id == R.id.btn_delete;
        boolean isCreate = id == R.id.btn_create;

        if (isCreate) {
            // 连接数据库，如果没有数据库则先创建
            SQLiteDatabase database = openOrCreateDatabase(databasePath, Context.MODE_PRIVATE, null);

            String format = "";
            if (database == null) {
                format = "数据库创建失败";
            } else {

                String path = database.getPath();
                format = String.format("数据库创建成功\n数据库地址：%s", path);
            }
            tvMessage.setText(format);
        } else if (isDelete) {
            boolean success = deleteDatabase(databasePath);
            if (success) {
                tvMessage.setText("删除成功");
            } else {
                tvMessage.setText("删除失败");
            }
        }

    }
}